package com.ruoyi.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 节假日json文件网址前缀
     */
    private static final String BASE_PREFIX = "https://gitee.com/holate/public-holiday/raw/master/holidays/year/";

    /**
     * 节假日json文件网址后缀
     */
    private static final String BASE_SUFFIX = ".json";

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 判断一天是不是节假日
     *
     * @param date 日期
     * @return true:休息日，false:工作日
     * @date 2022/02/04
     */
    public static boolean isHoliday(Date date, Map<Integer,Set<String>> map) {
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        cal.setTime(date);
        Integer year = cal.get(Calendar.YEAR);
        if (!map.keySet().contains(year)) {
            setHolidayForYear(year,map);
        }
        return isHoliday(cal,year,map);
    }

    /**
     * 通过年月查询第三方节假日，获取节日（和调休的工作日）
     *
     * @param year 年份
     * @return {@link Set <Calendar>}
     */
    @SuppressWarnings("unchecked")
    public static void setHolidayForYear(Integer year,Map<Integer,Set<String>> map) {
        //json对象，获取值使用的键
        String holiday = "holiday";
        //访问url
        String url = BASE_PREFIX + year + BASE_SUFFIX;
        String json = getUrl(url);
        if (json.length() == 0) {
            url = BASE_PREFIX + 2022 + BASE_SUFFIX;
            json = getUrl(url);
            if (json.length() == 0) {
                return;
            }
        }
        Set<String> LAW_HOLIDAYS = new HashSet<>();
        //构建json对象
        JSONObject body = JSON.parseObject(json);
        Map<String, JSONObject> days = (Map<String, JSONObject>) body.get(holiday);
        for (Map.Entry<String, JSONObject> entry : days.entrySet()) {
            Boolean isHoliday = (Boolean) entry.getValue().get(holiday);
            if (isHoliday) {
                LAW_HOLIDAYS.add(year + "-" + entry.getKey());
            }
//            else {
//                EXTRA_WORKDAYS.add(year + "-" + entry.getKey());
//            }
        }
        map.put(year,LAW_HOLIDAYS);
    }

    /**
     * 使用get请求访问url
     *
     * @param url 网址
     * @return {@link String} 返回响应内容
     */
    public static String getUrl(String url) {
        //访问返回结果
        StringBuilder result = new StringBuilder();
        //读取访问结果
        BufferedReader read = null;
        try {
            //创建url
            URL realUrl = new URL(url);
            //打开连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0");
            //建立连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), StandardCharsets.UTF_8));
            String line;//循环读取
            while ((line = read.readLine()) != null) {
                result.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeReader(read);
        }
        return result.toString();
    }

    /**
     * 关闭读取字符流
     *
     * @param reader 读取字符流
     */
    public static void closeReader(Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断一天是不是休息日
     *
     * @param cal 日期
     * @return true:休息日，false:工作日
     */
    public static boolean isHoliday(Calendar cal,Integer year,Map<Integer,Set<String>> map) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat(YYYY_MM_DD);
        String day = simpleFormat.format(cal.getTime());
        // 法定节假日必定是休息日
        if (map.get(year).contains(day)) {
            return true;
        }
        return false;
        // 排除法定节假日外的非周末必定是工作日
//        if (!isWeekend(cal)) {
//            return false;
//        }
        // 所有周末中只有非补班的才是休息日
//        return !EXTRA_WORKDAYS.contains(day);
    }
}
